﻿'Imports System.Web.UI.WebControls
'Imports System.Web.UI.WebControls.WebParts
'Imports System.Web.UI.HtmlControls
Imports ADOEntityImportData
Imports System.IO
Imports System.Data

Partial Class Administrator_frmImportLoginPic
    Inherits Web.UI.BasePage

#Region "Valiable"
    Private Enum chkStatus
        CountUploadFile
        UploadFile
        CanCel
    End Enum

    'Private Const pathDriveOnServer As String = "K:\\"
    Private PathFileOnServer As String = ""
    Private PathFileBackupOnServer As String = ""
    Dim convertDate As clsDateFormat
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim clsDatabase As clsDatabase
    Dim importDataEntity As ImportDataEntity
    Dim intBeforeItemIndex As Integer
#End Region

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            PathFileOnServer = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings("Path_KYC_LOGIN_INFO"))
            PathFileBackupOnServer = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings("Path_KYC_LOGIN_INFO_Bak"))

            btnUpload.Attributes.Add("onclick", "NoDoubleSubmit();")
            'btnDelete.Attributes.Add("onclick", "NoDoubleSubmit();")
            If Not IsPostBack Then
                chkIsLogin()
                CreateControlMP()
                setButton(1)
                BindData()
            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, _
                                                            Me.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)

        End Try
    End Sub


    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Try

            If chkBeforeSave() Then
                TxtPathFileUpload.Text = Path.GetFileName(FileUpload1.Value)

                clsSessionMenuRight = Session("ClsMenuRight")

                convertDate = New clsDateFormat
                Dim startDate As Date = convertDate.chkDateTimeThOrEn(clsDateFormat.enmDateCultureInfo.En, strDateIsChk:=txtStartDate.Text)
                Dim endDate As Date = convertDate.chkDateTimeThOrEn(clsDateFormat.enmDateCultureInfo.En, strDateIsChk:=txtEndDate.Text)

                Dim loginInfo As New KYC_LOGIN_INFO
                loginInfo.ID = GetKYC_LOGIN_INFOSeq()
                loginInfo.INFO_NAME = txtPictureName.Text
                loginInfo.FILE_NAME = TxtPathFileUpload.Text
                loginInfo.FILE_DESC = txtDesc.Text
                loginInfo.UPLOAD_BY = clsSessionMenuRight.getUserName
                loginInfo.UPLOAD_DATE = DateTime.Now
                loginInfo.ACTIVE_DATE = IIf(txtStartDate.Text = "", Nothing, startDate)
                loginInfo.EXPIRE_DATE = IIf(txtEndDate.Text = "", Nothing, endDate)
                loginInfo.ACTIVE_FLAG = "N"

                importDataEntity = New ImportDataEntity()
                importDataEntity.AddToKYC_LOGIN_INFO(loginInfo)
                importDataEntity.SaveChanges()

                uploadFileToServer(Path.GetFileNameWithoutExtension(TxtPathFileUpload.Text))
                BindData()
                ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('อัพโหลดสำเร็จ')", _
                                                    True)
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('" + ex.Message + "')", _
                                                True)
        End Try

    End Sub



#Region "SetForm"

    Sub CreateControlMP()
        Dim page As Label = CType(Master.FindControl("lblPage"), Label)
        page.Text = "จัดการไฟล์เอกสาร > นำเข้ารูปภาพหน้า Login"
    End Sub

    Private Sub setButton(ByVal button As Integer)

        If button = 1 Then 'unselect
            txtPictureName.Enabled = True
            txtStartDate.Enabled = True

            btnUpload.Enabled = True
            FileUpload1.Visible = True
            TxtPathFileUpload.Visible = False

            btnModify.Text = "แก้ไข"
            btnModify.Enabled = False
            btnDelete.Enabled = False
        ElseIf button = 2 Then 'select
            txtPictureName.Enabled = False

            btnUpload.Enabled = False
            FileUpload1.Visible = False

            TxtPathFileUpload.Visible = True
            'TxtPathFileUpload.Enabled = False

            btnModify.Enabled = True
            btnDelete.Enabled = True

        ElseIf button = 3 Then 'copy
            txtPictureName.Enabled = False

            btnUpload.Enabled = False
            FileUpload1.Visible = False

            TxtPathFileUpload.Visible = True

            btnModify.Enabled = True
            btnDelete.Enabled = False
        End If

    End Sub

    Private Sub reset()
        clearGvIndex()
        setButton(1)
        'lblMsg.Visible = False
        txtPictureName.Text = ""
        txtDesc.Text = ""
        txtStartDate.Text = ""
        txtEndDate.Text = ""
        TxtPathFileUpload.Text = ""
    End Sub

    Private Sub clearGvIndex()
        grdImportList.SelectedIndex = -1
    End Sub

#End Region


#Region " Function "
    Private Sub BindData()
        importDataEntity = New ImportDataEntity

        Dim UploadList = (From loginInfo In importDataEntity.KYC_LOGIN_INFO Order By loginInfo.ACTIVE_DATE Descending, loginInfo.UPLOAD_DATE Descending).ToList
        grdImportList.DataSource = UploadList
        grdImportList.DataBind()

        Session("uploadList") = UploadList
    End Sub

    Private Function checkInfoName(ByVal infoName As String) As Boolean
        Dim result As Boolean = True
        importDataEntity = New ImportDataEntity

        Dim count As Integer = (From loginInfo In importDataEntity.KYC_LOGIN_INFO Where loginInfo.INFO_NAME = infoName).Count

        If Not (count = 0) Then
            result = False
        End If

        Return result
    End Function

    Private Function checkFileName(ByVal fileName As String) As Boolean
        Dim result As Boolean = True
        importDataEntity = New ImportDataEntity

        Dim count As Integer = (From loginInfo In importDataEntity.KYC_LOGIN_INFO Where loginInfo.FILE_NAME = fileName).Count

        If Not (count = 0) Then
            result = False
        End If

        Return result
    End Function

    Private Function chkBeforeSave() As Boolean
        Dim result As Boolean = True

        If FileUpload1.PostedFile.ContentLength = 0 Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('กรุณาเลือกไฟล์ที่ต้องการอัพโหลด')", _
                                                True)
        ElseIf txtPictureName.Text = "" Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('กรุณาระบุชื่อไฟล์รูปภาพ')", _
                                                True)
        ElseIf Not checkInfoName(txtPictureName.Text) Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('มีชื่อรูปภาพนี้ในระบบแล้ว')", _
                                                True)
        ElseIf Not checkFileName(Path.GetFileName(FileUpload1.PostedFile.FileName)) Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('มีชื่อไฟล์นี้ในระบบแล้ว')", _
                                                True)
        Else
            result = checkDateBeforeSave(txtPictureName.Text, txtStartDate.Text, txtEndDate.Text)

        End If

        Return result
    End Function

    Private Function checkDateBeforeSave(ByVal infoName As String, ByVal strStartDate As String, ByVal strEndDate As String) As Boolean
        Dim result As Boolean = True
        convertDate = New clsDateFormat()

        Dim startDate As Date = Nothing
        Dim endDate As Date = Nothing

        If Not strStartDate = "" Then
            startDate = convertDate.chkDateTimeThOrEn(clsDateFormat.enmDateCultureInfo.En, strDateIsChk:=strStartDate)
        End If

        If Not strEndDate = "" Then
            endDate = convertDate.chkDateTimeThOrEn(clsDateFormat.enmDateCultureInfo.En, strDateIsChk:=strEndDate)
        End If

        If (Not strEndDate = "") And strStartDate = "" Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('กรุณาระบุวันที่ใช้งาน')", _
                                                True)
        ElseIf (Not strStartDate = "") And strEndDate = "" Then
            If Not convertDate.chkStartDateEndDate(Date.Now, startDate) Then
                result = False
                ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('วันที่ใช้งานต้องมากกว่าหรือเท่ากับวันที่ปัจจุบัน')", _
                                                    True)
            ElseIf Not checkTimeOverlap(infoName, startDate) Then
                result = False
                ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('วันที่ใช้งานทับกับช่วงวันที่ที่กำหนดไว้แล้ว')", _
                                                    True)
            End If
        ElseIf Not (strStartDate = "" Or strEndDate = "") Then
            If Not convertDate.chkStartDateEndDate(Date.Now, endDate) Then
                result = False
                ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('วันที่เลิกใช้งานต้องมากกว่าหรือเท่ากับวันที่ปัจจุบัน')", _
                                                    True)
            ElseIf Not convertDate.chkStartDateEndDate(startDate, endDate) Then
                result = False
                ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('วันที่เลิกใช้งานต้องมากกว่าหรือเท่ากับวันที่ใช้งาน')", _
                                                    True)
            ElseIf Not (checkTimeOverlap(infoName, startDate) AndAlso checkTimeOverlap(infoName, endDate)) Then
                result = False
                ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('วันที่ใช้งานทับกับช่วงวันที่ที่กำหนดไว้แล้ว')", _
                                                    True)
            End If
        End If

        Return result
    End Function

    Private Function checkTimeOverlap(ByVal infoName As String, ByVal pDate As Date) As Boolean
        Dim result As Boolean = True

        importDataEntity = New ImportDataEntity

        Dim count As Integer = (From loginInfo In importDataEntity.KYC_LOGIN_INFO _
                                Where loginInfo.INFO_NAME <> infoName _
                                And (loginInfo.ACTIVE_DATE <= pDate _
                                And loginInfo.EXPIRE_DATE >= pDate _
                                Or (Not loginInfo.ACTIVE_DATE Is Nothing And loginInfo.EXPIRE_DATE Is Nothing))
                                ).Count

        If count > 0 Then
            result = False
        End If

        Return result
    End Function

    Private Function checkCanDelete(ByVal activeDate As Date) As Boolean
        Dim result As Boolean = True

        If activeDate <= Date.Now Then
            result = False
        End If

        Return result
    End Function

    Private Sub uploadFileToServer(ByVal strFileName As String)
        Try
            Dim fn As String = ""
            Dim fnBackup As String = ""
            Dim strPathBatch As String = ""

            If (FileUpload1.Visible = True) Then
                TxtPathFileUpload.Text = FileUpload1.Value
            End If


            Dim strFileNameToSplit As String = TxtPathFileUpload.Text
            Dim arrString As String() = strFileNameToSplit.Split(".")
            fn = strFileName.Trim & "." & arrString(arrString.Length - 1)

            Dim savePath As String = Path.Combine(PathFileOnServer, fn)
            Dim backupPath As String = Path.Combine(PathFileBackupOnServer, fnBackup)

            If (FileUpload1.Visible = True) Then
                FileUpload1.PostedFile.SaveAs(savePath)
            Else
                ' FileUpload1.PostedFile.SaveAs(pathSanctionListBackOnServer & fnBackup)
                ' File.Copy( sourceFileName, DistributionFileName )
                If File.Exists(savePath) = True Then
                    If File.Exists(backupPath) = True Then
                        DeleteFile(backupPath)
                        File.Copy(savePath, backupPath)
                    Else
                        File.Copy(savePath, backupPath)
                    End If

                End If
            End If

        Catch ex As Exception
            WriteError(ex, "uploadFileToServer", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาดในการอัพโหลดไฟล์")
        End Try

    End Sub

    Private Function stringDate(ByVal strDate As String) As String
        Try
            Dim d() As String = strDate.Split("/")
            strDate = d(2) + d(1) + d(0)
        Catch ex As Exception
            WriteError(ex, "stringDate", "frmImportData")
        End Try
        Return strDate
    End Function

    Private Function FileExists(ByVal FileFullPath As String) As Boolean
        Try
            Dim f As New IO.FileInfo(FileFullPath)
            Return f.Exists
        Catch ex As Exception
            WriteError(ex, "FileExists", "frmImportData")

            Throw New Exception("เกิดข้อผิดพลาด FileExists ")
        End Try
    End Function

    Private Function DeleteFileInDirectory(ByVal targetDirectory As String) As Boolean
        Dim blnSuccess As Boolean = False
        Dim strTest As String = ""

        Try
            strTest = 1
            Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
            strTest = 2
            ' Process the list of files found in the directory.
            Dim fileName As String

            For Each fileName In fileEntries
                strTest = 3
                File.Delete(fileName)
            Next fileName
            strTest = 4
            blnSuccess = True
        Catch ex As Exception
            WriteError(ex, "DeleteFileInDirectory", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาด DeleteFileInDirectory " & strTest)
        End Try
        Return blnSuccess
    End Function

    Private Function DeleteFile(ByVal FileName As String) As Boolean
        Dim blnSuccess As Boolean = False
        Try
            File.Delete(FileName)
            blnSuccess = True
        Catch ex As Exception
            WriteError(ex, "DeleteFile", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาด DeleteFile ")
        End Try
        Return blnSuccess
    End Function

    Private Function readfile(ByVal FileFullPath As String) As String
        Dim strMsg As String = ""
        Try
            Dim srd As StreamReader = New System.IO.StreamReader(FileFullPath)
            strMsg = srd.ReadToEnd()
            srd.Close()
        Catch ex As Exception
            WriteError(ex, "readfile", "frmImportData")
            Throw New Exception("เกิดข้อผิดพลาด readfile ")
        End Try
        Return strMsg
    End Function


    Public Sub statusUpload(ByVal status As Integer)
        If (status = 0 Or status = 2) Then
            txtPictureName.Text = ""
            FileUpload1.Visible = True
            TxtPathFileUpload.Visible = False
            TxtPathFileUpload.Text = ""
            txtDesc.Text = ""
            txtStartDate.Text = ""
            txtEndDate.Text = ""
            btnUpload.Enabled = True
            BindData()

        ElseIf (status = 1) Then
            FileUpload1.Visible = False
            TxtPathFileUpload.Visible = True
        End If

    End Sub

    Private Function GetKYC_LOGIN_INFOSeq() As Decimal
        clsDatabase = New clsDatabase
        Dim sql As String = "select KYCADMIN.KYC_LOGIN_INFO_S.nextval from dual"
        Dim seq As Integer = clsDatabase.QueryDataTable(sql).Rows(0)("NEXTVAL")
        Return seq
    End Function
#End Region



    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        'ddlList.SelectedIndex = 0
        'FileUpload1.Visible = True
        'TxtPathFileUpload.Visible = False
        'TxtPathFileUpload.Text = ""
        'hdfUpload.Value = ""
        'hdfCountRow.Value = ""
        'btnTestUpload.Enabled = True
        'btnUpload.Enabled = False
        'lblCountRow.Text = ""
        statusUpload(0)
        setButton(1)
        clearGvIndex()
    End Sub

    Private Sub SaveLog(ByVal index As Integer)
        Try
            Dim program As String = "M73"
            Dim programName As String = " จัดการไฟล์เอกสาร > นำเข้ารูปภาพหน้า Login"

            Dim desc As String = ""

            If index = 3 Then
                desc = "บันทึก" + programName + " (นำเข้าข้อมูล " + txtPictureName.Text + ")"
            ElseIf index = 4 Then
                desc = "แก้ไข" + programName + " (นำเข้าข้อมูล " + txtPictureName.Text + ")"
            ElseIf index = 5 Then
                desc = "ลบ" + programName + " (นำเข้าข้อมูล " + txtPictureName.Text + ")"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, index, desc, program)


            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Protected Sub grdImportList_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdImportList.PageIndexChanging
        grdImportList.PageIndex = e.NewPageIndex
        clearGvIndex()
        grdImportList.DataSource = Session("uploadList")
        grdImportList.DataBind()
    End Sub

    Protected Sub grdImportList_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdImportList.RowCommand
        If e.CommandName = "Copy" Then
            clearGvIndex()
            Dim rowId As Integer = e.CommandArgument

            btnModify.Text = "บันทึก"

            setButton(3)

            hdfUploadID.Value = CType(grdImportList.Rows(rowId).FindControl("hdfID"), HiddenField).Value
            txtPictureName.Text = grdImportList.Rows(rowId).Cells(2).Text
            txtDesc.Text = grdImportList.Rows(rowId).Cells(4).Text.Replace("&nbsp;", "")
            txtStartDate.Text = ""
            txtEndDate.Text = ""
            TxtPathFileUpload.Text = grdImportList.Rows(rowId).Cells(3).Text

        End If
    End Sub

    Protected Sub grdImportList_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdImportList.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim link As HyperLink = e.Row.FindControl("linkImg")
            Dim loginInfo As KYC_LOGIN_INFO = e.Row.DataItem

            link.NavigateUrl = System.IO.Path.Combine(System.Configuration.ConfigurationManager.AppSettings("Path_KYC_LOGIN_INFO"), loginInfo.FILE_NAME)
        End If
    End Sub


    'Protected Sub grdImportList_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles grdImportList.RowCancelingEdit
    '    grdImportList.EditIndex = -1
    '    grdImportList.DataSource = Session("uploadList")
    '    grdImportList.DataBind()
    'End Sub

    'Protected Sub grdImportList_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grdImportList.RowDeleting
    '    importDataEntity = New ImportDataEntity
    '    Dim infoName = grdImportList.Rows(e.RowIndex).Cells(1).Text

    '    Dim qry = (From loginInfo In importDataEntity.KYC_LOGIN_INFO Where loginInfo.INFO_NAME = infoName).ToList

    '    If qry.Count > 0 Then
    '        importDataEntity.DeleteObject(qry(0))

    '        importDataEntity.SaveChanges()
    '    End If

    '    BindData()
    'End Sub


    'Protected Sub grdImportList_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles grdImportList.RowEditing
    '    grdImportList.EditIndex = e.NewEditIndex
    '    grdImportList.DataSource = Session("uploadList")
    '    grdImportList.DataBind()
    'End Sub

    'Protected Sub grdImportList_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles grdImportList.RowUpdating

    '    importDataEntity = New ImportDataEntity
    '    Dim infoName = grdImportList.Rows(e.RowIndex).Cells(1).Text

    '    Dim qry = (From loginInfo In importDataEntity.KYC_LOGIN_INFO Where loginInfo.INFO_NAME = infoName).ToList

    '    If qry.Count > 0 Then
    '        qry(0).FILE_DESC = e.NewValues.Item(0) ' txtDesc.Text
    '        qry(0).ACTIVE_DATE = txtStartDate.Text
    '        qry(0).EXPIRE_DATE = txtEndDate.Text
    '        importDataEntity.SaveChanges()
    '    End If

    '    grdImportList.EditIndex = -1
    '    BindData()
    'End Sub

    Protected Sub grdImportList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdImportList.SelectedIndexChanged
        If (grdImportList.SelectedIndex = intBeforeItemIndex) Then
            clearGvIndex()
            reset()

            btnModify.Text = "แก้ไข"
        Else
            btnModify.Text = "บันทึก"

            setButton(2)

            hdfUploadID.Value = CType(grdImportList.Rows(grdImportList.SelectedIndex).FindControl("hdfID"), HiddenField).Value
            txtPictureName.Text = grdImportList.Rows(grdImportList.SelectedIndex).Cells(2).Text
            txtDesc.Text = grdImportList.Rows(grdImportList.SelectedIndex).Cells(4).Text.Replace("&nbsp;", "")
            txtStartDate.Text = grdImportList.Rows(grdImportList.SelectedIndex).Cells(5).Text.Replace("&nbsp;", "")
            txtEndDate.Text = grdImportList.Rows(grdImportList.SelectedIndex).Cells(6).Text.Replace("&nbsp;", "")
            TxtPathFileUpload.Text = grdImportList.Rows(grdImportList.SelectedIndex).Cells(3).Text

            If Not txtEndDate.Text = "" Then
                convertDate = New clsDateFormat
                Dim startDate As Date = convertDate.chkDateTimeThOrEn(clsDateFormat.enmDateCultureInfo.En, strDateIsChk:=txtEndDate.Text)
                If convertDate.chkStartDateEndDate(startDate, Date.Now) Then
                    txtStartDate.Enabled = False
                End If
            End If

            btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resValidate.confirmDelete, _
                       IIf(grdImportList.SelectedIndex = -1, "", grdImportList.Rows(grdImportList.SelectedIndex).Cells(2).Text)) + "');")
        End If
    End Sub

    Protected Sub grdImportList_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdImportList.SelectedIndexChanging
        intBeforeItemIndex = grdImportList.SelectedIndex
    End Sub

    Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click
        Try
            If (Not grdImportList.SelectedIndex = -1) Then

                'Save Edit
                If checkDateBeforeSave(txtPictureName.Text, txtStartDate.Text, txtEndDate.Text) Then
                    importDataEntity = New ImportDataEntity
                    Dim infoName = txtPictureName.Text
                    Dim id = hdfUploadID.Value
                    convertDate = New clsDateFormat
                    Dim qry = (From loginInfo In importDataEntity.KYC_LOGIN_INFO Where loginInfo.ID = id).ToList

                    If qry.Count > 0 Then
                        qry(0).FILE_DESC = txtDesc.Text
                        If txtStartDate.Text = "" Then
                            qry(0).ACTIVE_DATE = Nothing
                        Else
                            qry(0).ACTIVE_DATE = convertDate.chkDateTimeThOrEn(clsDateFormat.enmDateCultureInfo.En, strDateIsChk:=txtStartDate.Text)
                        End If

                        If txtEndDate.Text = "" Then
                            qry(0).EXPIRE_DATE = Nothing
                        Else
                            qry(0).EXPIRE_DATE = convertDate.chkDateTimeThOrEn(clsDateFormat.enmDateCultureInfo.En, strDateIsChk:=txtEndDate.Text)
                        End If
                        importDataEntity.SaveChanges()
                    End If

                    SaveLog(4)

                    reset()
                    BindData()

                    ScriptManager.RegisterStartupScript(Me, _
                                                        Me.GetType(), _
                                                        "clientScript", _
                                                        "alert('" + Resources.resMsgKYC.msgSave + "')", _
                                                        True)
                End If
            Else
                'Save Copy
                If checkDateBeforeSave(txtPictureName.Text, txtStartDate.Text, txtEndDate.Text) Then
                    clsSessionMenuRight = Session("ClsMenuRight")

                    convertDate = New clsDateFormat
                    Dim startDate As Date = convertDate.chkDateTimeThOrEn(clsDateFormat.enmDateCultureInfo.En, strDateIsChk:=txtStartDate.Text)
                    Dim endDate As Date = convertDate.chkDateTimeThOrEn(clsDateFormat.enmDateCultureInfo.En, strDateIsChk:=txtEndDate.Text)

                    Dim loginInfo As New KYC_LOGIN_INFO
                    loginInfo.ID = GetKYC_LOGIN_INFOSeq()
                    loginInfo.INFO_NAME = txtPictureName.Text
                    loginInfo.FILE_NAME = TxtPathFileUpload.Text
                    loginInfo.FILE_DESC = txtDesc.Text
                    loginInfo.UPLOAD_BY = clsSessionMenuRight.getUserName
                    loginInfo.UPLOAD_DATE = DateTime.Now
                    loginInfo.ACTIVE_DATE = IIf(txtStartDate.Text = "", Nothing, startDate)
                    loginInfo.EXPIRE_DATE = IIf(txtEndDate.Text = "", Nothing, endDate)
                    loginInfo.ACTIVE_FLAG = "N"

                    importDataEntity = New ImportDataEntity()
                    importDataEntity.AddToKYC_LOGIN_INFO(loginInfo)
                    importDataEntity.SaveChanges()

                    SaveLog(3)

                    reset()
                    BindData()
                    ScriptManager.RegisterStartupScript(Me, _
                                                        Me.GetType(), _
                                                        "clientScript", _
                                                        "alert('" + Resources.resMsgKYC.msgSave + "')", _
                                                        True)
                End If
            End If

        Catch ex As System.Data.UpdateException
            ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('" + ex.InnerException.Message + "')", _
                                                    True)
            WriteError(ex, "btnModify_Click", "frmImportLoginPic")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)
            WriteError(ex, "btnModify_Click", "frmImportLoginPic")
        End Try
    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        If Not (grdImportList.SelectedIndex = -1) Then
            Dim infoName As String = grdImportList.Rows(grdImportList.SelectedIndex).Cells(2).Text
            Dim id As String = CType(grdImportList.Rows(grdImportList.SelectedIndex).FindControl("hdfID"), HiddenField).Value
            Dim strActiveDate As String = grdImportList.Rows(grdImportList.SelectedIndex).Cells(5).Text.Replace("&nbsp;", "")
            Dim activeDate As Date = Nothing
            If Not strActiveDate = "" Then
                activeDate = strActiveDate
            End If
            If strActiveDate = "" OrElse checkCanDelete(activeDate) Then
                Try
                    importDataEntity = New ImportDataEntity

                    Dim qry = (From loginInfo In importDataEntity.KYC_LOGIN_INFO Where loginInfo.ID = id).ToList

                    If qry.Count > 0 Then
                        importDataEntity.DeleteObject(qry(0))

                        importDataEntity.SaveChanges()
                    End If

                    SaveLog(5)

                    reset()
                    BindData()

                Catch ex As System.Data.UpdateException
                    Dim codeError() As String = ex.InnerException.Message.Split(":")
                    If codeError(0) = "ORA-02292" Then
                        ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('ไม่สามารถลบได้ เนื่องจากมีการนำมาใช้ในระบบแล้ว')", True)
                    Else
                        ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
                    End If
                    WriteError(ex, "btnDelete_Click", "frmImportLoginPic")
                Catch ex As Exception
                    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" + Resources.resError.errorMessage + "')", True)
                    WriteError(ex, "btnDelete_Click", "frmImportLoginPic")
                End Try
            Else
                ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('ไม่สามารถลบได้ เนื่องจากมีการนำมาใช้ในระบบแล้ว')", True)
            End If
        Else
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGridDelete + "')", True)

        End If
    End Sub
End Class
